
#include "texture_opengl.h"
#include "canvas.h"

using namespace krryn::system_imp;
using namespace krryn::view;

texture_opengl::texture_opengl(canvas *a_Canvas) : texture(a_Canvas){
	glEnable(GL_TEXTURE_2D);
	glGenTextures(1, &m_TextureId);
	glBindTexture(GL_TEXTURE_2D, m_TextureId);

	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
	glTexParameteri(GL_TEXTURE_2D, GL_GENERATE_MIPMAP, GL_TRUE);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, m_WrapU == texture_repeat ? GL_REPEAT : GL_CLAMP);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, m_WrapV == texture_repeat ? GL_REPEAT : GL_CLAMP);

	// load texture into opengl
	glTexImage2D(
		GL_TEXTURE_2D, 
		0, 
		GL_RGBA8, 
		m_Canvas->get_width(),
		m_Canvas->get_height(), 
		0,
		GL_RGBA,
		GL_UNSIGNED_INT_8_8_8_8_REV,
		(GLubyte*)m_Canvas->get_buffer()
	);
}

texture_opengl::~texture_opengl(){
	glDeleteTextures(1, &m_TextureId);
}

void texture_opengl::enable(){
	// TODO: Move this somewhere it makes sense
	glActiveTexture(GL_TEXTURE0 + (GLenum)0);
	glClientActiveTexture(GL_TEXTURE0 + (GLenum)0);
	glBindTexture(GL_TEXTURE_2D, m_TextureId);
}

void texture_opengl::disable(){
	glBindTexture(GL_TEXTURE_2D, 0);
}